package cart

import (
	"mallgo/core"
	"mallgo/internal/common/response"
	"mallgo/internal/resources/cart/api/apis"
	"mallgo/internal/resources/cart/api/domain/request"
	"strconv"

	"github.com/gin-gonic/gin"
)

type CartController struct {
	cartApi apis.CartApi
}

func NewCartController(cartApi apis.CartApi) *CartController {
	return &CartController{
		cartApi: cartApi,
	}
}

// AddToCart 添加商品到购物车
func (c *CartController) AddToCart(ctx *gin.Context) {
	var req request.CartAddRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(200, response.Error(400, "参数错误"))
		return
	}
	res := c.cartApi.AddToCart(&req)
	ctx.JSON(200, res)
}

// UpdateCart 更新购物车
func (c *CartController) UpdateCart(ctx *gin.Context) {
	var req request.CartUpdateRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(200, response.Error(400, "参数错误"))
		return
	}
	res := c.cartApi.UpdateCart(&req)
	ctx.JSON(200, res)
}

// DeleteCart 删除购物车商品
func (c *CartController) DeleteCart(ctx *gin.Context) {
	cartId := ctx.Param("id")
	id, _ := strconv.ParseInt(cartId, 10, 64)
	res := c.cartApi.DeleteCart(id)
	ctx.JSON(200, res)
}

// ListCart 获取购物车列表
func (c *CartController) ListCart(ctx *gin.Context) {
	userId := ctx.Query("userId")
	id, _ := strconv.ParseInt(userId, 10, 64)
	res := c.cartApi.ListCart(id)
	ctx.JSON(200, res)
}

// InitRouter 初始化路由
func InitRouter(cartController *CartController, s *core.AppServer) {
	api := s.Engine.Group("/api/cart")
	{
		api.POST("", cartController.AddToCart)
		api.PUT("", cartController.UpdateCart)
		api.DELETE("/:id", cartController.DeleteCart)
		api.GET("", cartController.ListCart)
	}
}
